package com.njust.RateMyTray_backend.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.njust.RateMyTray_backend.entity.Dish;
import com.njust.RateMyTray_backend.vo.DishRatingVO;
import com.njust.RateMyTray_backend.vo.TopRatedDishVO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface DishMapper extends BaseMapper<Dish> {
    
    @Select("SELECT d.id as dishId, d.dish_name as name, AVG(c.rating) as averageRating " +
            "FROM t_dish d " +
            "LEFT JOIN t_comment c ON d.id = c.target_id AND c.target_type = 'dish' " +
            "GROUP BY d.id, d.dish_name " +
            "ORDER BY averageRating DESC " +
            "LIMIT 5")
    List<TopRatedDishVO> findTopRatedDishes();
    
    @Select("SELECT d.id as dishId, d.dish_name as dishName, " +
            "AVG(c.rating) as averageRating, COUNT(c.id) as totalComments " +
            "FROM t_dish d " +
            "LEFT JOIN t_comment c ON d.id = c.target_id AND c.target_type = 'dish' " +
            "WHERE d.window_id = #{windowId} " +
            "GROUP BY d.id, d.dish_name")
    List<DishRatingVO> findDishRatingsByWindowId(@Param("windowId") Long windowId);

    @Select("<script>" +
            "SELECT d.* FROM t_dish d WHERE d.id IN (" +
            "SELECT dt.dish_id " +
            "FROM t_dish_tag dt " +
            "JOIN t_tag t ON dt.tag_id = t.id " +
            "WHERE t.tag_name IN " +
            "<foreach item='item' index='index' collection='tagNames' open='(' separator=',' close=')'>#{item}</foreach> " +
            "GROUP BY dt.dish_id " +
            "HAVING COUNT(DISTINCT t.id) = #{tagCount}" +
            ")</script>")
    List<Dish> findDishesByTagNames(@Param("tagNames") List<String> tagNames, @Param("tagCount") int tagCount);
} 